package com.baikeyang.app.controller.api.QingFM.v1;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.baikeyang.common.bean.ResponseResult;
import com.baikeyang.common.bean.map.baidu.BaiduGeocodingResult;
import com.baikeyang.common.bean.map.baidu.BaiduReverseGeocodingResult;
import com.baikeyang.common.bean.qingFM.*;
import com.baikeyang.common.constant.ExecuteConstants;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;

/**
 * Created by lenovo on 2018/5/31.
 */
@RestController(value = "v1Index")
@RequestMapping(value = "app/v1/radio/fm")
public class IndexController {

    private static final String HTTP_SERVER_URL = "http://rapi.qingting.fm/";
    private static final String LIVE_SERVER_URL = "http://lhttp.qingting.fm/";
    private static final String BAIDUMAP_SERVER_URL = "http://api.map.baidu.com/reverse_geocoding/v3/";

    /**
     * 根据经纬度获取位置信息
     * @param lng <经度>
     * @param lat <纬度>
     * @return
     */
    @RequestMapping(value = "area")
    public ResponseResult area(String lng, String lat) {
        ResponseResult result = new ResponseResult();
        String _key = "GpkoT53F4ZCKwpAwBaHGGhR3UVblhcgO";
        String _url = BAIDUMAP_SERVER_URL + "?ak=" + _key + "&output=json&coordtype=wgs84ll&location=" + lat + "," + lng;
        String body = HttpUtil.get(_url, Charset.forName("UTF-8"));
        // {"status":0,"result":{"location":{"lng":108.95094659783713,"lat":34.345948598929428},"formatted_address":"陕西省西安市未央区凤城八路","business":"张家堡,城市运动公园,未央路沿线","addressComponent":{"country":"中国","country_code":0,"country_code_iso":"CHN","country_code_iso2":"CN","province":"陕西省","city":"西安市","city_level":2,"district":"未央区","town":"","town_code":"","adcode":"610112","street":"凤城八路","street_number":"","direction":"","distance":""},"pois":[],"roads":[],"poiRegions":[],"sematic_description":"","cityCode":233}}
        System.out.println(body);
        BaiduReverseGeocodingResult reverseGeocodingResult = JSON.parseObject(body, BaiduReverseGeocodingResult.class);
        if(reverseGeocodingResult.getStatus().equals(0)){
            BaiduGeocodingResult baiduGeocodingResult = reverseGeocodingResult.getResult();
            String _a = "";
            if(null != baiduGeocodingResult.getAddressComponent()){
                _a = baiduGeocodingResult.getAddressComponent().getProvince();
            }
            result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.成功, ExecuteConstants.EXECUTEINFO.成功, ExecuteConstants.EXECUTECODE.CODE_200, _a);
        } else {
            result = new ResponseResult(reverseGeocodingResult.getStatus().toString(), ExecuteConstants.EXECUTECODE.CODE_501);
        }
        return result;
    }

    /**
     * 获取地域列表
     * @return
     */
    @RequestMapping(value = "regions")
    public ResponseResult regions (HttpServletRequest request, HttpServletResponse response) {
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = headerNames.nextElement();
            String value = request.getHeader(key);
        }
        String timestamp = request.getHeader("timestamp");
        String test = request.getHeader("test");
        //Enumeration<String> paramNames = request.getParameterNames();



        //http://rapi.qingting.fm/regions
        ResponseResult result = new ResponseResult();
        String url = "http://rapi.qingting.fm/regions";
        try{
            String body = HttpUtil.get(url, Charset.forName("UTF-8"));
            RegionsResult regionsResult = JSON.parseObject(body, RegionsResult.class);
            if(regionsResult.getSuccess().equals("ok")){
                result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.成功, ExecuteConstants.EXECUTEINFO.成功, ExecuteConstants.EXECUTECODE.CODE_200, regionsResult.getData());
            }else {
                result = new ResponseResult(regionsResult.getSuccess(), ExecuteConstants.EXECUTECODE.CODE_501);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result = new ResponseResult("获取地域列表时发生异常", ExecuteConstants.EXECUTECODE.CODE_500);
        }
        return result;
    }

    /**
     * 获取电台频道分类列表
     * @return
     */
    @RequestMapping(value = "channel")
    public ResponseResult getChannel () {
        ResponseResult result = new ResponseResult();
        String url = "http://rapi.qingting.fm/categories";
        url += "?type=channel";
        try{
            String body = HttpUtil.get(url, Charset.forName("UTF-8"));
            ChannelResult channelResult = JSON.parseObject(body, ChannelResult.class);
            if(channelResult.getSuccess().equals("ok")){
                result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.成功, ExecuteConstants.EXECUTEINFO.成功, ExecuteConstants.EXECUTECODE.CODE_200, channelResult.getData());
            }else {
                result = new ResponseResult(channelResult.getSuccess(), ExecuteConstants.EXECUTECODE.CODE_501);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result = new ResponseResult("获取电台频道分类列表时发生异常", ExecuteConstants.EXECUTECODE.CODE_500);
        }
        return result;
    }

    /**
     * 获取电台网络频道列表
     * @return
     */
    @RequestMapping(value = "program")
    public ResponseResult getProgram () {
        ResponseResult result = new ResponseResult();
        String url = "http://rapi.qingting.fm/categories";
        url += "?type=program";
        try{
            String body = HttpUtil.get(url, Charset.forName("UTF-8"));
            ProgramResult programResult = JSON.parseObject(body, ProgramResult.class);
            if(programResult.getSuccess().equals("ok")){
                result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.成功, ExecuteConstants.EXECUTEINFO.成功, ExecuteConstants.EXECUTECODE.CODE_200, programResult.getData());
            }else {
                result = new ResponseResult(programResult.getSuccess(), ExecuteConstants.EXECUTECODE.CODE_501);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result = new ResponseResult("获取电台网络频道列表时发生异常", ExecuteConstants.EXECUTECODE.CODE_500);
        }
        return result;
    }

    /**
     * 获取指定频道中电台列表
     * @param channel 频道类别ID
     * @param page 页数
     * @param pagesize 每页显示条数
     * @param showTotal 是否返回总条数
     * @return
     */
    @RequestMapping(value = "channels")
    public ResponseResult getChannels (Integer channel,Integer page, Integer pagesize, Integer showTotal) {
        //http://rapi.qingting.fm/categories/259/channels?with_total=true&page=1&pagesize=12
        ResponseResult result = new ResponseResult();
        if(null == channel){
            return new ResponseResult("频道类别ID不允许为空", ExecuteConstants.EXECUTECODE.CODE_400);
        }
        String url = HTTP_SERVER_URL + "categories/"+ channel + "/channels?";
        boolean isShowPageNum = false;
        if(null == showTotal || 0 != showTotal){// false 或者不传递，均不返回总条数
            isShowPageNum = true;
        }
        if(null == page)page = 1;
        if(null == pagesize)pagesize = 10;
        url += "with_total=" + isShowPageNum + "&page=" + page + "&pagesize=" + pagesize;
        try{
            String body = HttpUtil.get(url, Charset.forName("UTF-8"));
            QingResult qingResult = new QingResult();
            if(isShowPageNum){
                qingResult = JSON.parseObject(body, ChannelsPageResult.class);
            }else {
                qingResult = JSON.parseObject(body, ChannelsResult.class);
            }

            if(qingResult.getSuccess().equals("ok")){
                result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.成功, ExecuteConstants.EXECUTEINFO.成功, ExecuteConstants.EXECUTECODE.CODE_200, qingResult.getData());
            }else {
                result = new ResponseResult(qingResult.getSuccess(), ExecuteConstants.EXECUTECODE.CODE_501);
            }
        }catch (Exception e) {
            e.printStackTrace();
            result = new ResponseResult("获取指定频道中电台列表时发生异常", ExecuteConstants.EXECUTECODE.CODE_500);
        }
        return result;
    }

    /**
     * 获取所有的
     * @return
     */
    @RequestMapping(value = "categories")
    public ResponseResult getCategories (){
        ResponseResult result = new ResponseResult();
        String url = "https://i.qingting.fm/capi/search/keywords";
        try{
            String body = HttpUtil.get(url, Charset.forName("UTF-8"));
            ChannelCategory regionsResult = JSON.parseObject(body, ChannelCategory.class);
//            if(regionsResult.getSuccess().equals("ok")){
//                result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.成功, ExecuteConstants.EXECUTEINFO.成功, ExecuteConstants.EXECUTECODE.CODE_200, regionsResult.getData());
//            }else {
//                result = new ResponseResult(regionsResult.getSuccess(), ExecuteConstants.EXECUTECODE.CODE_501);
//            }
        }catch (Exception e) {
            e.printStackTrace();
            result = new ResponseResult("获取地域列表时发生异常", ExecuteConstants.EXECUTECODE.CODE_500);
        }
        return result;
    }

    @RequestMapping(value = "crosstalk/classes")
    public ResponseResult getCrosstalkChannels (){
        ResponseResult result = new ResponseResult();
        String url = "https://i.qingting.fm/capi/neo-channel-filter?category=527&attrs=0&curpage=1";
        try{
            String body = HttpUtil.get(url, Charset.forName("UTF-8"));
            ChannelCategory regionsResult = JSON.parseObject(body, ChannelCategory.class);
//            if(regionsResult.getSuccess().equals("ok")){
//                result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.成功, ExecuteConstants.EXECUTEINFO.成功, ExecuteConstants.EXECUTECODE.CODE_200, regionsResult.getData());
//            }else {
//                result = new ResponseResult(regionsResult.getSuccess(), ExecuteConstants.EXECUTECODE.CODE_501);
//            }
        }catch (Exception e) {
            e.printStackTrace();
            result = new ResponseResult("获取地域列表时发生异常", ExecuteConstants.EXECUTECODE.CODE_500);
        }
        return result;
    }

    /**
     * 获取直播流地址
     * @param id
     * @return
     */
    @RequestMapping(value = "live")
    public ResponseResult getLive (Integer id) {
        // http://lhttp.qingting.fm/live/{id}/64k.mp3
        ResponseResult result = new ResponseResult();
        if(null == id){
            return new ResponseResult("电台ID不允许为空", ExecuteConstants.EXECUTECODE.CODE_400);
        }
        String url = LIVE_SERVER_URL + "live/"+ id + "/64k.mp3";
        return result = new ResponseResult(ExecuteConstants.EXECUTESTATUS.成功, ExecuteConstants.EXECUTEINFO.成功, ExecuteConstants.EXECUTECODE.CODE_200, url);
    }











//    正在热播：
//    http://rapi.qingting.fm/recommendations/0/channel_list?more=true&replay=false
//
//    听回听：
//    http://rapi.qingting.fm/recommendations/0/replay_list?more=true&replay=true


    @RequestMapping(value = "")
    public ModelAndView showFm() {
        return new ModelAndView("/radioFm/fm-v1");
    }

    @RequestMapping(value = "/index")
    public ModelAndView index() {
        return new ModelAndView("/radioFm/fm-v1");
    }

    /**
     * 获取类别列表
     * @param type :
     *             1、channel
     *             2、program
     * @return
     */
    @Deprecated
    public ResponseResult getCategories (Integer type) {
        ResponseResult result = new ResponseResult();
//        String url = "http://rapi.qingting.fm/categories";
//        Object classObj = null;
//        String typeProgram = "";
//        if(1 == type){
//            typeProgram = "channel";
//            classObj = new ChannelResult();
//        }else if(2 == type){
//            typeProgram = "program";
//            classObj = new ProgramResult();
//        }
//
//        if(StringUtils.isEmpty(typeProgram)){
//            return new ResponseResult("type 不允许为空", Constants.EXECUTECODE.CODE_400);
//        }
//
//        url += "?type=" + typeProgram;
//
//        HttpClientTest t = new HttpClientTest();
//        try{
////            String body = HttpClientTest.sendGetData(url, "utf-8");
////            QingResult qingResult = JSON.parseObject(body, classObj.getClass());
////            if(regionsResult.getSuccess().equals("ok")){
////                result = new ResponseResult(Constants.EXECUTESTATUS.成功, Constants.EXECUTEINFO.成功, Constants.EXECUTECODE.CODE_200, regionsResult.getData());
////            }else {
////                result = new ResponseResult(regionsResult.getSuccess(), Constants.EXECUTECODE.CODE_501);
////            }
//        }catch (Exception e) {
//            e.printStackTrace();
//            result = new ResponseResult("获取地域列表时发生异常", Constants.EXECUTECODE.CODE_500);
//        }
        return result;

    }


    public static void main(String[] args) {
        String str = "T_LOG_VIDEO,"+
            "T_LOG_CAR_ERROR,"+
            "T_LOG_CAR_LIMIT,"+
            "T_LOG_CAR_NO,"+
            "T_LOG_COMPANY_LIMIT,"+
            "T_LOG_IMPORT,"+
            "T_LOG_OPERATE,"+
            "T_LOG_RELIEF_SEND,"+
            "T_LOG_VERSION,"+
            "T_LOG_VIDEO,"+
            "T_B_USER_LOGO,"+
            "T_B_VEHICLE_FWD_STATE,"+
            "T_B_VIDEO_PARAM,"+
            "T_B_VIDEOTAPE,"+
            "T_CURR_ALARM,"+
            "T_DEL_CAR_DRIVER,"+
            "T_LOG_ALARM_HANDLELOG,"+
            "T_B_IMAGE_INFO,"+
            "T_B_LOCK_INFO,"+
            "T_B_LOCK_INFO_LOG,"+
            "T_B_LOG_INFO,"+
            "T_B_LOGIN_NUM,"+
            "T_B_MARK,"+
            "T_B_MARK_TYPE,"+
            "T_B_NOTICE,"+
            "T_B_OIL_PARAM,"+
            "T_B_OIL_PARAM_DETAIL,"+
            "T_B_PARTIAL_LINE,"+
            "T_B_PARTNER_INFO,"+
            "T_B_PARTNER_VEHICLE,"+
            "T_B_PATH,"+
            "T_B_PATH_LOG,"+
            "T_B_PATH_TASK_INFO,"+
            "T_B_PLATALARM_SET,"+
            "T_B_PLATFORM_DYNAMIC_INFO,"+
            "T_B_PROVINCE,"+
            "T_B_RELIEF_INFO,"+
            "T_B_ROLE,"+
            "T_B_SERVICE_STATION_INFO,"+
            "T_B_SPEEDLIMITED_INFO,"+
            "T_B_SUBTITLE_INFO,"+
            "T_B_SYS_CONFIG,"+
            "T_B_TAKE_DRIVE_INFO,"+
            "T_B_TAKE_EWAYBILL,"+
            "T_B_TASK_INFO,"+
            "T_B_TERMINAL_INSTRUCTION,"+
            "T_B_TERMINAL_SIM,"+
            "T_B_UPDATE_RECORD,"+
            "T_B_USER,"+
            "T_B_USER_ALARMSET,"+
            "T_B_USER_LOGO,"+
            "T_B_VEHICLE_FWD_STATE,"+
            "T_B_VIDEO_PARAM,"+
            "T_B_VIDEOTAPE,"+
            "T_CURR_ALARM,"+
            "T_DEL_CAR_DRIVER,"+
            "T_LOG_ALARM_HANDLELOG,"+
            "T_LOG_CAR_ERROR,"+
            "T_LOG_CAR_LIMIT,"+
            "T_B_FUNC,"+
            "T_B_GPS_TASK,"+
            "T_B_HIGHSPEED_SECTION,"+
            "T_B_HISTORY_MESSAGE,"+
            "T_B_IC_CARD,"+
            "T_B_IMAGE_INFO,"+
            "T_B_CAR_LINE_TASK,"+
            "T_B_CAR_LINE_TASK_LOG,"+
            "T_B_CAR_OWNER,"+
            "T_B_CAR_REGISTER_INFO,"+
            "T_B_CAR_REPLACE_SIM_LOG,"+
            "T_B_CHARGES_PACKAGE,"+
            "T_B_CITY,"+
            "T_B_CLOUD_DATATYPE,"+
            "T_B_CODE,"+
            "T_B_CODE_TYPE,"+
            "T_B_COMMONLY_MESSAGE,"+
            "T_B_COMPANY,"+
            "T_B_COMPANY_MODE,"+
            "T_B_DB_ALARM,"+
            "T_B_DRIVER,"+
            "T_B_FACTORY,"+
            "T_B_FEEDBACK,"+
            "T_B_FIRST_INDEX,"+
            "T_B_FLOW_STAT_INFO,"+
            "T_B_FUNC,"+
            "T_B_GPS_TASK,"+
            "T_B_HIGHSPEED_SECTION,"+
            "T_B_HISTORY_MESSAGE,"+
            "T_B_IC_CARD,"+
            "T_B_IMAGE_INFO,"+
            "T_B_LOCK_INFO,"+
            "T_B_LOCK_INFO_LOG,"+
            "T_B_LOG_INFO,"+
            "T_B_LOGIN_NUM,"+
            "T_B_MARK,"+
            "T_B_MARK_TYPE,"+
            "T_B_NOTICE,"+
            "T_B_OIL_PARAM,"+
            "T_B_OIL_PARAM_DETAIL,"+
            "T_B_PARTIAL_LINE,"+
            "T_B_PARTNER_INFO,"+
            "T_B_PARTNER_VEHICLE,"+
            "T_B_PATH,"+
            "T_B_PATH_LOG,"+
            "T_B_PATH_TASK_INFO,"+
            "T_B_PLATALARM_SET,"+
            "T_B_PLATFORM_DYNAMIC_INFO,"+
            "T_B_PROVINCE,"+
            "T_B_RELIEF_INFO,"+
            "T_B_ROLE,"+
            "T_B_SERVICE_STATION_INFO,"+
            "T_B_SPEEDLIMITED_INFO,"+
            "T_B_SUBTITLE_INFO,"+
            "T_B_SYS_CONFIG,"+
            "T_B_FLOW_STAT_INFO,"+
            "T_S_HIS_ALARM_INFO,"+
            "T_S_ALARM_INFO,"+
            "T_MODIFY_NOTICE,"+
            "T_MODIFY_PUBLISHER,"+
            "T_O_DEV_DAY,"+
            "T_O_DEV_FUEL,"+
            "T_PROC_EXEC_ENDTIME,"+
            "T_REL_ALARM_ORG,"+
            "T_REL_ALARM_USER,"+
            "T_REL_AREA_CAR,"+
            "T_REL_AREA_ORG,"+
            "T_REL_CAR_DRIVER,"+
            "T_REL_CHARGES_CAR,"+
            "T_REL_LINE_CAR,"+
            "T_REL_PLATALARM_CAR,"+
            "T_REL_RELIEF_CAR,"+
            "T_REL_ROLE_FUNC,"+
            "T_REL_SUBTITLE_CAR,"+
            "T_REL_USER_CAR,"+
            "T_REL_USER_ORG,"+
            "T_REL_USER_REPORT_FIELD,"+
            "T_REL_USERDEFINE_FUNC,"+
            "T_B_ALARM_SCORE_CONFIG,"+
            "T_B_ALARMTYPE,"+
            "T_B_AREA,"+
            "T_B_AREA_ROAD,"+
            "T_B_ATTENTION_CAR,"+
            "T_B_ATTENTION_ORG,"+
            "T_B_CAR_INFO";
        String[] sts = str.split(",");
        List<String> ss = new ArrayList<String>();
        for(int i = 0; i < sts.length; i++){
            if(!ss.contains(sts[i])){
                ss.add(sts[i]);
            }
        }
        System.out.println(ss);
        System.out.println(ss.size());
    }

}
